package com.home.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.home.demo.dao.MenuDao;
import com.home.demo.entity.MenuAndRoleEntity;
import com.home.demo.entity.MenuEntity;
import com.home.demo.entity.vo.menu.MenuTreeVO;
import com.home.demo.service.MenuAndRoleService;
import com.home.demo.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service("menuService")
@Slf4j
public class MenuServiceImpl extends ServiceImpl<MenuDao, MenuEntity> implements MenuService {
    @Autowired
    private MenuAndRoleService menuAndRoleService;



    /**
     * 保存菜单信息->不携带parent_id的时候就是父级菜单 为"0"
     * @param menu
     */
    @Override
    public void saveInfo(MenuEntity menu) {
        if (menu!=null && !StringUtils.hasText(menu.getParentId())) {
            menu.setParentId("0");
        }
        this.save(menu);
    }

    /**
     * 删除菜单详情, 同时删除角色与菜单的关联
     * @param id
     */
    @Override
    @Transactional
    public void removeByIdsInfo(String id) {
        List<MenuEntity> list = this.list();
        List<String> ids = new ArrayList<>();
        ids.add(id);
        list.stream().filter(e->e.getId().equals(id)).forEach(e->{
            childrenMenuIdS(e.getId(),list,ids);
        });
        this.removeBatchByIds(ids);

        menuAndRoleService.remove(new QueryWrapper<MenuAndRoleEntity>().in(ids!=null&&ids.size()>0,"menu_id", ids));

    }
    private List<String> childrenMenuIdS(String id,List<MenuEntity> list,List<String> ids){
        list.stream().forEach(e->{
            if (e.getParentId().equals(id)){
                ids.add(e.getId());
                childrenMenuIdS(e.getId(),list,ids);
            }

        });
        return ids;
    }


    @Override
    public List<MenuTreeVO> getMenuTree() {
        List<MenuEntity> list = this.list();
        return BeanUtil.copyToList(list, MenuTreeVO.class).stream().filter(e -> e.getParentId().equals("0")).map(e -> {
            e.setChildren(menuTree(e, BeanUtil.copyToList(list, MenuTreeVO.class)));
            return e;
        }).collect(Collectors.toList());

    }


    private   List<MenuTreeVO> menuTree( MenuTreeVO parent,List<MenuTreeVO> all){
       return all.stream().filter(e->{
           return parent.getId().equals(e.getParentId());
        }).map(e->{
            e.setChildren(menuTree(e,all));
            return e;
        }).collect(Collectors.toList());
    }


}